﻿using Newtonsoft.Json;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using VisionDesigner;
using VM.Common.Enums;
using VM.Common.EventMgrLib;
using VM.Common.Helper;
using VM.Start.Attributes;
using VM.Start.Common;
using VM.Start.Core;
using VM.Start.Events;
using VM.Start.Models;
using VM.Start.ViewModels;

namespace Plugin.ExportImage
{
    #region enum
    public enum eLinkCommand
    {
        InputModuleLink
    }

    #endregion

    [Category("常用工具")]
    [DisplayName("输出图像")]
    [ModuleImageName("ExportImage")]
    [JsonObject(MemberSerialization.OptOut)]
    public class ExportImageViewModel : ModuleBase
    {
        #region 属性
        /// <summary>
        /// 参数
        /// </summary>
        private ExportModel _Param;
        public ExportModel Param
        {
            get
            {
                if (_Param == null)
                {
                    _Param = new ExportModel();
                }
                return _Param;
            }
            set
            {
                Set(ref _Param, value);
            }
        }
        /// <summary>
        /// 图片文件夹路径
        /// </summary>
        private string _FilePath;
        public string FilePath
        {
            get { return _FilePath; }
            set { _FilePath = value; RaisePropertyChanged(); }
        }
        public string fullfilepath;

        #endregion

        #region 数据接口
        private string _ImagePath;
        public string ImagePath
        {
            get => _ImagePath;
            set
            {
                if (_ImagePath != value)
                {
                    _ImagePath = value;
                    RaisePropertyChanged(nameof(ImagePath));
                }
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private MVDRenderActivex _MvdRender;
        [Newtonsoft.Json.JsonIgnore]
        public MVDRenderActivex? MvdRender
        {
            get => _MvdRender;
            set => _MvdRender = value;
        }

        static class FunctionCounter
        {
            public static int ExecutionCount { get; private set; }
            public static void Increment() => ExecutionCount++;
        }

        #endregion

        #region 指令
        /// <summary>
        /// 确定指令
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ConfirmCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ConfirmCommand
        {
            get
            {
                if (_ConfirmCommand == null)
                {
                    _ConfirmCommand = new CommandBase((obj) =>
                    {
                        var view = this.ModuleView as ExportImageView;
                        if (view != null)
                        {
                            view.Close();
                        }
                    });
                }
                return _ConfirmCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _FilePathCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase FilePathCommand
        {
            get
            {
                if (_FilePathCommand == null)
                {
                    _FilePathCommand = new CommandBase((obj) =>
                    {
                        FolderBrowserDialog folderDialog = new FolderBrowserDialog();
                        if (folderDialog.ShowDialog() == DialogResult.OK)
                        {
                            FilePath = folderDialog.SelectedPath;
                        }
                    });
                }
                return _FilePathCommand;
            }
        }


        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _LinkCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase LinkCommand
        {
            get
            {
                if (_LinkCommand == null)
                {
                    //以GUID+类名作为筛选器
                    EventMgr.Ins.GetEvent<VarChangedEvent>().Subscribe(OnVarChanged, o => o.SendName.StartsWith($"{ModuleGuid}"));
                    _LinkCommand = new CommandBase((obj) =>
                    {
                        eLinkCommand linkCommand = (eLinkCommand)obj;
                        switch (linkCommand)
                        {
                            case eLinkCommand.InputModuleLink:
                                CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "");
                                for (int j = VarLinkViewModel.Ins.Modules.Count - 1; j >= 0; j--)
                                {
                                    var displayName = VarLinkViewModel.Ins.Modules[j].DisplayName;
                                    if (displayName.Contains("输出图像") || displayName.Contains("条件分支") || displayName.Contains("位置修正")
                                        || displayName.Contains("接收文本") || displayName.Contains("发送文本") || displayName.Contains("如果")
                                        || displayName.Contains("否则如果") || displayName.Contains("否则") || displayName.Contains("结束"))
                                    {
                                        VarLinkViewModel.Ins.Modules.RemoveAt(j);
                                    }
                                }
                                EventMgr.Ins.GetEvent<OpenVarLinkViewEvent>().Publish($"{ModuleGuid},InputModuleLink");
                                break;
                            default:
                                break;
                        }
                    });
                }
                return _LinkCommand;
            }
        }

        #endregion

        #region 方法
        public override void Loaded()
        {
            base.Loaded();
            var view = ModuleView as ExportImageView;
            if (view != null)
            {
                ClosedView = true;
                SetDefaultLink();
                if (InputModuleLinkText == null) return;
            }
        }

        public void GetWindow(string ModuleLinkText, string RunState)
        {
            if (ModuleLinkText == null)
                return;
            ModuleBase var = Prj.GetModuleByName(ModuleLinkText);
            if (var == null)
                return;
            if (var.ModuleParam.Status.ToString() == RunState || RunState == "ALL")
            {
                MvdRender = var.mWindowH.MVDRender;
            }
            else
            {
                MvdRender = null;
            }
            if (MvdRender == null)
                return;
        }

        public override void SetDefaultLink()
        {
            if (InputModuleLinkText == null)
            {
                CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "");
                for (int j = VarLinkViewModel.Ins.Modules.Count - 1; j >= 0; j--)
                {
                    var displayName = VarLinkViewModel.Ins.Modules[j].DisplayName;
                    if (displayName.Contains("输出图像") || displayName.Contains("条件分支") || displayName.Contains("位置修正")
                        || displayName.Contains("接收文本") || displayName.Contains("发送文本") || displayName.Contains("如果")
                        || displayName.Contains("否则如果") || displayName.Contains("否则") || displayName.Contains("结束"))
                    {
                        VarLinkViewModel.Ins.Modules.RemoveAt(j);
                    }
                }
                var moduls = VarLinkViewModel.Ins.Modules.LastOrDefault();
                if (moduls?.VarModels.Count > 0)
                {
                    InputModuleLinkText = $"{moduls.DisplayName}";
                }
            }
        }

        private void OnVarChanged(VarChangedEventParamModel obj)
        {
            switch (obj.SendName.Split(',')[1])
            {
                case "InputModuleLink":
                    InputModuleLinkText = obj.LinkName.Split('&', '.')[1];
                    if (InputModuleLinkText == null) return;
                    break;
                default:
                    break;
            }
        }

        public override bool ExeModule()
        {
            try
            {
                Stopwatch.Restart();
                if (InputModuleLinkText == null)
                {
                    SetDefaultLink();
                }
                if (FilePath == null || InputModuleLinkText == null)
                {
                    ChangeModuleRunStatus(eRunStatus.NG);
                    return false;
                }
                else
                {
                    string runstate = Param.RunStatu switch
                    {
                        "OK" => "OK",
                        "NG" => "NG",
                        "ALL" => "ALL",
                        _ => throw new ArgumentException($"未知的执行状态: {Param.RunStatu}")
                    };
                    GetWindow(InputModuleLinkText, runstate);
                    if (MvdRender == null)
                    {
                        ChangeModuleRunStatus(eRunStatus.NG);
                        return false;
                    }
                    if (Param.SaveName == "序号")
                    {
                        FunctionCounter.Increment();
                    }
                    // 根据保存名称生成文件路径
                    string fullFilePath = Param.SaveName switch
                    {
                        "无" => $"{FilePath}/{ImagePath}",
                        "序号" => $"{FilePath}/{ImagePath}-{FunctionCounter.ExecutionCount}",
                        "时间" => $"{FilePath}/{ImagePath}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss}",
                        _ => throw new ArgumentException($"未知的保存名称: {Param.SaveName}")
                    };
                    string extension = Param.SaveFormat switch
                    {
                        "BMP" => ".bmp",
                        "JPEG" => ".jpg",
                        _ => throw new ArgumentException($"未知的保存格式: {Param.SaveFormat}")
                    };
                    if (Param.SaveFormat == "BMP")
                    {
                        MvdRender.SaveImage(fullFilePath + extension, MVD_FILE_FORMAT.MVD_FILE_BMP, 1, MVD_SAVE_TYPE.MVD_SAVE_RESULT_IMAGE);
                    }
                    if (Param.SaveFormat == "JPEG")
                    {
                        MvdRender.SaveImage(fullFilePath + extension, MVD_FILE_FORMAT.MVD_FILE_JPEG, 1, MVD_SAVE_TYPE.MVD_SAVE_RESULT_IMAGE);
                    }
                }
                ChangeModuleRunStatus(eRunStatus.OK);
                return true;
            }
            catch
            {
                ChangeModuleRunStatus(eRunStatus.NG);
                return false;
            }
        }

        public override bool ExeModule(string TemplateName)
        {
            return ExeModule();
        }

        /// <summary>
        /// 添加结果
        /// </summary>
        public override void AddOutputParams()
        {
            AddOutputParam("状态", "bool", ModuleParam.Status == eRunStatus.OK ? true : false);
            AddOutputParam("时间", "int", ModuleParam.ElapsedTime);
        }
        #endregion
    }
}
